package cn.wen233.srpc.core.execute.client;

import cn.wen233.srpc.basic.model.Request;
import cn.wen233.srpc.basic.model.Response;
import cn.wen233.srpc.core.execute.ClientExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * ObjectInputStream
 *
 * @author wenei
 * @date 2021-10-28 12:08
 */
public class NativeSerializeClientExecutor implements ClientExecutor {

    private static final Logger LOGGER = LoggerFactory.getLogger(NativeSerializeClientExecutor.class);

    @Override
    public Response doExecute(Request request) {
        Response response = null;
        try {
            Socket socket = new Socket();
            InetSocketAddress address = new InetSocketAddress(request.getHost(), request.getPort());
            socket.connect(address);
            new ObjectOutputStream(socket.getOutputStream()).writeObject(request);
            // 单向关闭Output 避免死锁
            // 如果直接关闭输入或者输出流，即：in.close()或者out.close()，会直接关闭socket
            socket.shutdownOutput();
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            response = (Response) objectInputStream.readObject();
            socket.close();
        } catch (IOException | ClassNotFoundException e) {
            LOGGER.warn("TCP 连接时出现异常：", e);
        }

        return response;
    }
}
